﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace OntologyCache
{
    public class CacheManager
    {
        public static void CreateNewPersistentCache(string OBOFileName, string TagFileName, string OntologyName)
        {
            OntologyInfo thetags = LoadNonCachedTags(OntologyName, OBOFileName);
            if (thetags != null)
            {
                using (FileStream fs = new FileStream(TagFileName, FileMode.Create))
                {
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(fs, thetags);
                    fs.Close();
                }
            }
        }


        public static OntologyInfo LoadNonCachedTags(string OntologyName, string FileName)
        {
            if (false == File.Exists(FileName))
            {
                return null;
            }
            OntologyInfo thetags = new OntologyInfo();
            try
            {
                OBOParser parser = new OBOParser();
                thetags.OntologyName = OntologyName;

                parser.Parse(FileName, thetags, OntologyName);
            }
            catch (Exception ex)
            {
                thetags = null;
            }
            return thetags;
        }

        public static OntologyInfo LoadTagsFromCache(string CacheFileName, bool TryCreate,string OntologyName)
        {
            OntologyInfo thetags = null;
            try
            {
                if (false == File.Exists(CacheFileName))
                {
                    // hmm so no precompuation exists
                    if (TryCreate == true)
                    {
                        CreateNewPersistentCache(Path.ChangeExtension(CacheFileName, "obo"), CacheFileName,OntologyName);
                    }
                    else
                    {
                        return null;
                    }
                }
                using (FileStream fs = new FileStream(CacheFileName, FileMode.Open))
                {
                    BinaryFormatter formatter = new BinaryFormatter();

                    // Deserialize the hashtable from the file and 

                    thetags = (OntologyInfo)formatter.Deserialize(fs);
                    fs.Close();
                }
            }
            catch (Exception Ex)
            {

            }

            return thetags;

        }



        
    }
}
